//
//  HomepageSetting.swift
//  YoruNeko
//
//  Created by Kotori on 2021/6/21.
//

import SwiftUI

struct HomepageSetting: View {
    //@EnvironmentObject var userStorage: UserModelData
    
    @State var selectedOption: String = Homepage.getHomepageOption()[0]
    @State var homepageUrl: String = ""
    
    let homepageOptions = Homepage.getHomepageOption()
    let currUserMgr = UserManager.currUserMgr
    
    var body: some View {
        List {
            ForEach(homepageOptions, id: \.self) { option in
                HStack {
                    Text(option)
                        .frame(width: 300, height: 40, alignment: .leading)
                        .background(Color.white)
                    Spacer()
                    if(option == selectedOption) {
                        Image(systemName: "checkmark.circle.fill")
                            .foregroundColor(/*@START_MENU_TOKEN@*/.blue/*@END_MENU_TOKEN@*/)
                    }
                }
                .onTapGesture {
                    selectedOption = option
                }
            }
            
            //last为自定义标签页
            if selectedOption == homepageOptions.last {
                TextField("在此输入URL", text: $homepageUrl)
                    .disableAutocorrection(true)
                    .autocapitalization(.none)
            }
            
        }
        .onAppear {
            selectedOption = homepageOptions[currUserMgr.getHomeSelectIndex()]
            if currUserMgr.getHomeSelectIndex() == homepageOptions.count-1 {
                homepageUrl = currUserMgr.getHomeList()[0]["url"] as! String
            }
        }
        .toolbar(content: {
            Button {
                //写入到偏好设置中
                let index = Homepage.getHomepageOption().firstIndex(of: selectedOption)
                currUserMgr.setHomeSelectIndex(index: index ?? 0)
                if(index == Homepage.getHomepageOption().count - 1) {
                    //暂不知道setHomeList正确用法
                    currUserMgr.setHomeList(list: [["url": homepageUrl]])
                }
                currUserMgr.commit()
            } label: {
                Text("保存")
            }
            .alert(isPresented: .constant(false), content: {
                Alert(title: Text("已保存"))
            })
        })
        
    }
}

struct HomepageSetting_Previews: PreviewProvider {
    static var previews: some View {
        HomepageSetting()
    }
}
